import { Context } from "koa";
import Schema, { Rules, Values } from "async-validator";

const validate = async <T extends Values>(
  ctx: Context,
  rulers: Rules
): Promise<{
  data: T;
  error: any;
}> => {
  const validator = new Schema(rulers);
  let data={} as any
  switch (ctx.request.method) {
    case "POST":
     data = ctx.request.body || {};
      break;
      case "DELETE":
        data = ctx.query || {};
        break;
        case "GET":
          data = ctx.query|| {};
          break;
          case "PUT":
            data = ctx.request.body || {};
            break;
  
    default:
      break;
  }
 
  return await validator
    .validate(JSON.parse(JSON.stringify(data)))
    .then(() => {
      return {
        data: data as T,
        error: null,
      };
    })
    .catch((err) => {
      return {
        data: err||{} as T,
        error: err.errors[0].message,
      };
    });
};

export { validate };
